/**
 * 代码库信息概览
 */

import React from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { Overlay, Button, Tab, Message, Input, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import { getWebIdeUrl } from 'api';
import track from 'utils/track';
import { ENUM } from 'utils/constants.js';
import exceed from 'utils/apimap';
import utils from 'utils';
import { getPathWithRootPath, navigateOpen } from 'utils/router';
import { getFeature } from 'utils/features';
import PersonalSettings from 'components/PersonalSettings';
import './index.scss';
import intl from '../../../../../../../../locale';

const { visibility_levels } = ENUM;
const https_notset_repo_ids = 'https-notset-repo-ids';
const ssh_notset_repo_ids = 'ssh-notset-repo-ids';

// 按钮全部禁用
const btnDisabledTip = intl.get({
  id: 'code-assets.containers.repoOverviewInfo.cloneBtn.CloneDownloadControlIsEnabled',
  defaultMessage: '已开启克隆下载控制，请通过 WebIDE 或页面编辑、浏览',
});
// 禁止克隆或下载单个提示文本
const btnDisabledCopyOrDownloadTip = intl.get({
  id: 'code-assets.containers.repoOverviewInfo.cloneBtn.CloneDownloadControlIsEnabled.1',
  defaultMessage: '已开启克隆下载控制，请通过其他方式操作',
});

export default class RepoOverviewInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeTitleIndex: 'SSH',
    };
  }

  beforeOpen = () => {
    this.getHttpsAccountAgain();
    this.getKeys();
  };

  /**
   * 在个人设置（在吊顶里面）中配置完HTTPS密码之后，当前页下的httpsAccount未更新，
   * 所以在“克隆/下载”的hover弹层中，如果account_type仍然是'no_https_secret'，则需要去再查询一次
   */
  getHttpsAccountAgain = () => {
    if (this.noHttpsSecret()) {
      this.props.getHttpsAccount();
    }
  };

  noHttpsSecret = () => {
    const { httpsAccount } = this.props;
    return !!(httpsAccount && httpsAccount.account_type === 'no_https_secret');
  };

  filterLevel = (level) => {
    let label = '';
    visibility_levels.forEach((item) => {
      if (item.value === Number(level)) {
        label = item.label;
      }
    });
    return label;
  };

  // 下载的下拉菜单
  renderDownloadDropdownJsx(isGuest) {
    const { isEmpty, project_clone_download } = this.props;
    const { pathResource, resourceSubject } = window.FORCE;
    if (isEmpty || isGuest) {
      return null;
    }

    if (project_clone_download) {
      const isDisabledDownload =
        project_clone_download.downloadLimit &&
        project_clone_download.downloadLimit.state === 'disable';

      if (isDisabledDownload) {
        return (
          <React.Fragment>
            <Balloon.Tooltip
              align="t"
              text={btnDisabledCopyOrDownloadTip}
              trigger={
                <Button
                  type="secondary"
                  component="a"
                  disabled
                  className="gitClone-download-btn download-zip"
                >
                  {intl.get({
                    id: 'code-assets.containers.repoOverviewInfo.cloneBtn.DownloadZip',
                    defaultMessage: '下载 ZIP',
                  })}
                </Button>
              }
            />

            <span className="gitClone-download-btn-line"> </span>
            <Balloon.Tooltip
              align="t"
              text={btnDisabledCopyOrDownloadTip}
              trigger={
                <Button
                  type="secondary"
                  className="gitClone-download-btn download-tar"
                  component="a"
                  disabled
                >
                  {intl.get({
                    id: 'code-assets.containers.repoOverviewInfo.cloneBtn.DownloadTar',
                    defaultMessage: '下载 TAR',
                  })}
                </Button>
              }
            />
          </React.Fragment>
        );
      }
    }

    return (
      <React.Fragment>
        <Button
          type="secondary"
          component="a"
          href={getPathWithRootPath(`/${pathResource.fullPath}/repository/archive.zip?ref=${encodeURIComponent(
            resourceSubject.revision,
          )}`)}
          className="gitClone-download-btn download-zip"
          onClick={() => {
            track({
              action: 'download',
              page: 'Repo-Files',
              control: 'download - zip',
            });
          }}
        >
          {intl.get({
            id: 'code-assets.containers.repoOverviewInfo.cloneBtn.DownloadZip',
            defaultMessage: '下载 ZIP',
          })}
        </Button>
        <span className="gitClone-download-btn-line"> </span>
        <Button
          type="secondary"
          className="gitClone-download-btn download-tar"
          component="a"
          href={getPathWithRootPath(`/${pathResource.fullPath}/repository/archive.tar.gz?ref=${encodeURIComponent(
            resourceSubject.revision,
          )}`)}
          onClick={() => {
            track({
              action: 'download',
              page: 'Repo-Files',
              control: 'download - tar',
            });
          }}
        >
          {intl.get({
            id: 'code-assets.containers.repoOverviewInfo.cloneBtn.DownloadTar',
            defaultMessage: '下载 TAR',
          })}
        </Button>
      </React.Fragment>
    );
  }

  goWebIde = (e, path) => {
    const { resourceSubject } = window.FORCE;
    const { revisionType } = resourceSubject;
    e.preventDefault();
    getWebIdeUrl({
      filepath: path,
      branch: revisionType === 'branch' ? resourceSubject.revision : '',
      commit: revisionType === 'sha1' ? resourceSubject.revision : '',
      line: '',
      column: '',
      type: 'view',
      merge_commit: '',
      mergerequestId: '',
    })
      .then((result) => {
        navigateOpen(result.endpoint);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  getKeys = () => {
    exceed
      .forceFetch({
        api: 'keys.list',
        data: {
          page: 1,
          per_page: 10,
        },
      })
      .then((result) => {
        this.setState({
          keys: result.list,
        });
      });
  };

  setCachedRepoIds = (key) => {
    const ids = this.getCachedRepoIds(key);
    const valueItem = this.getCachedRepoValue();
    if (!ids.includes(valueItem)) {
      ids.push(valueItem);
    }
    utils.setCachedData(key, JSON.stringify(ids));
  };

  getCachedRepoValue = () => {
    const { pathResource, user } = window.FORCE;
    return `${pathResource.id}_${user.codeUserId}`;
  };

  getCachedRepoIds = (key) => {
    const curIdStr = utils.getCachedData(key);
    if (curIdStr) {
      return JSON.parse(curIdStr);
    }
    return [];
  };

  renderViewUsername = () => {
    if (!getFeature('personal.settings.httpsPw')) {
      return getFeature('personal.settings.httpsPw.message');
    }

    let viewUsername = (
      <div>
        {intl.get({
          id: 'code-assets.containers.repoOverviewInfo.cloneBtn.UseTheEmailAddressOr',
          defaultMessage: '用户名请使用帐号设置中的邮箱或手机帐号。',
        })}
        <a
          href="https://account.teambition.com/my/account"
          target="_blank"
          className="https-clone-message-link"
          rel="noreferrer"
        >
          {intl.get({
            id: 'code-assets.containers.repoOverviewInfo.cloneBtn.ViewUserNames',
            defaultMessage: '查看用户名',
          })}
        </a>
      </div>
    );

    if (this.noHttpsSecret()) {
      viewUsername = (
        <div>
          未配置 HTTPS 克隆密码，
          <PersonalSettings
            type="httpsPw"
            className="ssh-notset-message-link"
          >
            去设置
          </PersonalSettings>
        </div>
      );
    } else {
      viewUsername = (
        <div>
          {intl.get({
            id: 'code-assets.containers.repoOverviewInfo.cloneBtn.ForgotToCloneAnAccount',
            defaultMessage: '忘记克隆账号或密码？',
          })}

          <PersonalSettings
            type="httpsPw"
            className="ssh-notset-message-link"
          >
            {intl.get({
              id: 'code-assets.containers.repoOverviewInfo.cloneBtn.ViewNow',
              defaultMessage: '立即查看',
            })}
          </PersonalSettings>
        </div>
      );
    }

    return viewUsername;
  };

  renderSshMessage = () => {
    const { activeTitleIndex } = this.state;
    const { keys } = this.state;
    const sshMsgClose = this.getCachedRepoIds(ssh_notset_repo_ids).includes(
      this.getCachedRepoValue(),
    );

    if (activeTitleIndex === 'SSH' && !sshMsgClose && keys) {
      return (
        <Message
          className={`ssh-notset-message ${keys.length ? 'one-line' : ''}`}
          type={keys.length === 0 ? 'warning' : 'notice'}
          closeable
          onClose={() => {
            this.setCachedRepoIds(ssh_notset_repo_ids);
          }}
        >
          {keys.length === 0 ? (
            <div>
              {intl.get({
                id: 'code-assets.containers.repoOverviewInfo.cloneBtn.NoSshKeyIsConfigured',
                defaultMessage: '未配置 SSH 密钥，',
              })}
              <PersonalSettings
                className="ssh-notset-message-link"
                type="ssh"
              >
                去设置
              </PersonalSettings>
            </div>
          ) : (
            <div>
              {intl.get({
                id: 'code-assets.containers.repoOverviewInfo.cloneBtn.ManageSshKeys',
                defaultMessage: '管理 SSH 密钥？',
              })}

              <PersonalSettings
                className="ssh-notset-message-link"
                type="ssh"
              >
                {intl.get({
                  id: 'code-assets.containers.repoOverviewInfo.cloneBtn.ViewNow',
                  defaultMessage: '立即查看',
                })}
              </PersonalSettings>
            </div>
          )}
        </Message>
      );
    }

    return null;
  };

  render() {
    const { projectInfo, httpsAccount, project_clone_download } = this.props;
    const { activeTitleIndex } = this.state;
    const { pathResource } = window.FORCE;
    const dataSource = [
      {
        title: 'SSH',
        address: projectInfo.ssh_url_to_repo,
      },

      {
        title: 'HTTPS',
        address: projectInfo.http_url_to_repo,
      },
    ];

    // TODO 用户身份结合仓库私有还是公开，决定最终权限
    let isPrivate = true;
    if (
      ENUM.visibility_level_text[projectInfo.visibility_level] &&
      ENUM.visibility_level_text[projectInfo.visibility_level] !== 'private'
    ) {
      isPrivate = false;
    }

    const isGuest = pathResource.role === 'Guest';
    const httpsMsgClose = this.getCachedRepoIds(https_notset_repo_ids).includes(
      this.getCachedRepoValue(),
    );
    const noAliyunHttpsSecret = !(httpsAccount && httpsAccount.account_type === 'no_https_secret');

    // 集团内根据接口返回判断是否可用
    let isDisabledSsh = false;
    let isDisabledHttps = false;
    let isDisabledDownload = false;
    const disabledBtn = (
      <Button type="primary" disabled>
        <YunxiaoIcon type="arrow-down-line" />
        {intl.get({
          id: 'code-assets.containers.repoOverviewInfo.cloneBtn.CloneDownload',
          defaultMessage: '克隆/下载',
        })}
        <YunxiaoIcon type="trilateral-down-fill" />
      </Button>
    );

    if (!project_clone_download) {
      return disabledBtn;
    }
    isDisabledSsh =
      project_clone_download.sshCloneLimit &&
      project_clone_download.sshCloneLimit.state === 'disable';
    isDisabledHttps =
      project_clone_download.httpCloneLimit &&
      project_clone_download.httpCloneLimit.state === 'disable';
    isDisabledDownload =
      project_clone_download.downloadLimit &&
      project_clone_download.downloadLimit.state === 'disable';

    if (isDisabledSsh && isDisabledHttps && isDisabledDownload) {
      return (
        <Balloon.Tooltip align="t" trigger={disabledBtn}>
          {btnDisabledTip}
        </Balloon.Tooltip>
      );
    }

    const isDisableCopy =
      (activeTitleIndex === 'SSH' && isDisabledSsh) ||
      (activeTitleIndex === 'HTTPS' && isDisabledHttps);

    return (
      <React.Fragment>
        <Overlay.Popup
          beforeOpen={this.beforeOpen}
          trigger={
            <Button type="primary">
              {intl.get({
                id: 'code-assets.containers.repoOverviewInfo.cloneBtn.CloneDownload',
                defaultMessage: '克隆/下载',
              })}
              <YunxiaoIcon type="arrow-down-2-line" />
            </Button>
          }
          triggerType="click"
          safeNode={'personal-setting-dialog'}
        >
          <div className="clone-popup overlay-shadow">
            <Tab activeKey={activeTitleIndex} animation={false}>
              {dataSource.map((data) => (
                <Tab.Item
                  title={data.title}
                  key={data.title}
                  onClick={(key) => {
                    this.setState({ activeTitleIndex: key });
                  }}
                >
                  {activeTitleIndex === 'HTTPS' && !httpsMsgClose && (
                    <Message
                      className={`https-clone-message ${noAliyunHttpsSecret ? 'one-line' : ''}`}
                      type={
                        httpsAccount && httpsAccount.account_type === 'no_https_secret'
                          ? 'warning'
                          : 'notice'
                      }
                      closeable
                      onClose={() => {
                        this.setCachedRepoIds(https_notset_repo_ids);
                      }}
                    >
                      {this.renderViewUsername()}
                    </Message>
                  )}

                  {this.renderSshMessage()}
                  <div className="clone-popup-content">
                    <Input
                      className="gitClone-address-input"
                      value={dataSource.find((item) => item.title === activeTitleIndex).address}
                      readOnly
                    />

                    {isDisableCopy ? (
                      <Balloon.Tooltip
                        align="t"
                        trigger={
                          <Button
                            type="normal"
                            className="gitClone-copy-btn"
                            disabled
                            onClick={() => {}}
                          >
                            <YunxiaoIcon type="copy-line" />
                          </Button>
                        }
                      >
                        {btnDisabledCopyOrDownloadTip}
                      </Balloon.Tooltip>
                    ) : (
                      <CopyToClipboard
                        text={dataSource.find((item) => item.title === activeTitleIndex).address}
                        onCopy={() => {
                          track({
                            action: activeTitleIndex === 'SSH' ? 'copy_ssh' : 'copy_https',
                            page: 'Repo-Files',
                            type: '',
                            control: '',
                          });

                          Message.success({
                            title: intl.get({
                              id: 'code-assets.containers.repoOverviewInfo.cloneBtn.CopiedSuccessfully',
                              defaultMessage: '复制成功',
                            }),
                          });
                        }}
                      >
                        <Button type="normal" className="gitClone-copy-btn" onClick={() => {}}>
                          <YunxiaoIcon type="copy-line" />
                        </Button>
                      </CopyToClipboard>
                    )}
                  </div>
                </Tab.Item>
              ))}
            </Tab>
            {this.renderDownloadDropdownJsx(isGuest, isPrivate)}
          </div>
        </Overlay.Popup>
      </React.Fragment>
    );
  }
}
